package com.lfy.kcat.workflow.ai.impl;

import com.lfy.kcat.workflow.ai.OllamaModerationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class DeepSeekModerationServiceImpl implements OllamaModerationService {

    /**
     *
     *
     */
    // 保持现有的@Value注解，但添加默认值以防配置缺失
    @Value("${deepseek.api.key:sk-b36497cf27524c7884259d3c376e12d7}")
    private String deepSeekApiKey;

    @Value("${deepseek.api.url:https://api.deepseek.com/v1/chat/completions}")
    private String deepSeekApiUrl;

    private final RestTemplate restTemplate = new RestTemplate();

        @Override
    public String moderation(String content) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", List.of(
                Map.of("role", "system", "content", "你是一个内容安全审核助手，请分析以下内容是否包含敏感、违法或不适当的信息。如果内容安全，请回复\"1\"；如果内容不安全，请回复\"0\"。只回复1或0，不要包含其他内容。"),
                Map.of("role", "user", "content", content)
            ));
            requestBody.put("temperature", 0.1);
            requestBody.put("max_tokens", 10);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(deepSeekApiKey);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

            // 发送请求
            ResponseEntity<Map> response = restTemplate.postForEntity(deepSeekApiUrl, request, Map.class);

            // 解析响应
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                    String result = (String) message.get("content");
                    String cleanResult = result.trim();

                    // 确保返回值是1或0
                    if (cleanResult.contains("0")) {
                        return "0";
                    } else {
                        return "1";
                    }
                }
            }

            log.warn("DeepSeek API返回格式异常，使用默认通过: {}", responseBody);
            return "1"; // 默认安全
        } catch (Exception e) {
            log.error("调用DeepSeek API进行内容审核失败，使用默认通过策略", e);
            return "1"; // 出错时默认通过
        }
    }

}
